package com.example.capsule_netty.service;

import com.example.capsule_netty.bean.GroupMessageBean;
import com.example.capsule_netty.bean.MessageBean;
import com.example.capsule_netty.bean.OneToOneMessageBean;
import com.example.capsule_netty.configuration.Constant;
import com.example.capsule_netty.configuration.KafkaConstant;
import com.example.capsule_netty.global.GlobalThreadPool;
import com.example.capsule_netty.global.UserAndChannelRelevance;
import com.example.capsule_netty.impl.MessageActionImpl;
import com.example.capsule_netty.mapper.GroupMessageMapper;
import com.example.capsule_netty.mapper.OneToOneMessageMapper;
import com.google.gson.Gson;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFutureCallback;

import javax.annotation.Resource;
import java.io.*;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @Author: zhuzhiming
 * @Date: 2022/5/4 0:04
 */
@Service
@Slf4j
public class OneToOneMessageService {

    @Resource
    OneToOneMessageMapper oneToOneMessageMapper;

    @Autowired
    KafkaTemplate<String, String> kafkaTemplate;

    @Autowired
    MessageActionImpl messageActionImpl;

    @Autowired
    UserAndChannelRelevance userAndChannelRelevance;


    public String getMessages(String roomName) {

        List<OneToOneMessageBean> oneToOneBeanList = oneToOneMessageMapper.getMessagesList(roomName);

        CompletableFuture.runAsync(()->{
           oneToOneMessageMapper.updateMessageStatus(roomName);
        });

        return new Gson().toJson(oneToOneBeanList);

    }

    public void saveMessage(MessageBean messageBean) {

        if (messageBean.getMsgType() != 0) {

            if (messageBean.getMsgType() != -1 && !messageBean.isOneToOne()) {
                GlobalThreadPool.buildThreadPool().execute(new Runnable() {
                    @Override
                    public void run() {
                        kafkaTemplate.send(KafkaConstant.SAVE_MESSAGE_TOPIC, new Gson().toJson(messageBean)).addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
                            @Override
                            public void onFailure(Throwable ex) {
                                log.error("send save message failure");
                            }

                            @Override
                            public void onSuccess(SendResult<String, String> result) {
                                //    log.info("send save message success");
                            }
                        });

                    }
                });
            }

            if (messageBean.getMsgType() != -1) {
                GlobalThreadPool.buildThreadPool().execute(new Runnable() {
                    @Override
                    public void run() {
                        String imei = messageBean.getImei();
                        Channel channel = userAndChannelRelevance.getChannelFromImei(imei);
                        MessageBean copyBean = new MessageBean();
                        BeanUtils.copyProperties(messageBean, copyBean);
                        messageActionImpl.dealChatAction(channel, copyBean);
                    }
                });
            }

            OutputStream out = null;

            if (messageBean.getMsgType() == 1) {
                if (!new File(Constant.IMAGE_PATH).exists()) {
                    new File(Constant.IMAGE_PATH).mkdirs();
                }
                try {
                    out = new FileOutputStream(Constant.IMAGE_PATH + "/" + messageBean.getFileName());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            } else if (messageBean.getMsgType() == 2) {
                if (!new File(Constant.FILE_PATH).exists()) {
                    new File(Constant.FILE_PATH).mkdirs();
                }
                try {
                    out = new FileOutputStream(Constant.FILE_PATH + messageBean.getFileName());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            } else if (messageBean.getMsgType() == 3 || messageBean.getMsgType() == -1) {
                if (!new File(Constant.VIDEO_PATH).exists()) {
                    new File(Constant.VIDEO_PATH).mkdirs();
                }
                try {
                    out = new FileOutputStream(Constant.VIDEO_PATH + messageBean.getFileName());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }

            try {
                byte[] by = Base64.getDecoder().decode(messageBean.getContent());
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out);
                bufferedOutputStream.write(by);
                bufferedOutputStream.flush();
                bufferedOutputStream.close();
                out.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }

    public String updateMessageStatus(String roomName) {
        oneToOneMessageMapper.updateMessageStatus(roomName);
        return Constant.SUCCESS;
    }
}
